package pri.abner.practice.thread.sequentialexecution;

import java.util.concurrent.CountDownLatch;

/**
 *@description 使用CountDownLatch 保证顺序执行
 *@author abner chow
 *@date 2019-08-30 11:39
 */
public class Execution2 {

    public static void main(String[] args) {

        CountDownLatch c0 = new CountDownLatch(0);
        CountDownLatch c1 = new CountDownLatch(1);
        CountDownLatch c2 = new CountDownLatch(1);

        //c0为0，t1可以执行。t1的计数器减1
        Thread t1 = new Thread(new Work(c0, c1), "Thread one");
        //t1的计数器为0时，t2才能执行。t2的计数器c2减1
        Thread t2 = new Thread(new Work(c1, c2), "Thread two");
        Thread t3 = new Thread(new Work(c2, c2), "Thread three");

        t1.start();
        t2.start();
        t3.start();

    }


    //定义Work线程类，需要传入开始和结束的CountDownLatch参数
    static class Work implements Runnable {

        CountDownLatch c0;
        CountDownLatch c1;

        Work(CountDownLatch c0, CountDownLatch c1) {
            this.c0 = c0;
            this.c1 = c1;
        }

        @Override
        public void run() {
            try {
                //前一线程为0才可以执行
                c0.await();
                System.out.println(Thread.currentThread().getName() + " start...");
                c1.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}
